package com.geelee.startup.processor

import com.geelee.startup.annotation.model.DependencyChain
import java.io.File
import javax.annotation.processing.ProcessingEnvironment
import javax.tools.StandardLocation


/**
 * Created by zhiyueli on 2021/8/13.
 *
 * 初始化器报告生成器，将在 doc 目录下生成初始化器注册表
 */
class InitializerReporter(
    private val mainThreadComponentChainList: List<DependencyChain>,
    private val workThreadComponentChainList: List<DependencyChain>
) {

    fun outputReport(processingEnv: ProcessingEnvironment) {
        val sb = StringBuilder("*Auto generated by APT. DO NOT EDIT!*").appendln()
        sb.appendln(mainThreadComponentChainList.listToString("## 主线程初始化器依赖链："))
        sb.appendln(workThreadComponentChainList.listToString("## 子线程初始化器依赖链："))
        val reportFile = processingEnv.filer.createResource(
            StandardLocation.SOURCE_OUTPUT,
            "",
            "report.md"
        )
        File(reportFile.toUri()).writeText(sb.toString())
    }

    private fun List<DependencyChain>.listToString(title: String): String {
        if (this.isEmpty()) {
            return ""
        }
        val sb = StringBuilder()
        sb.appendln(title)
        sb.appendln("#### 初始化顺序：从上往下，有依赖关系的，从右往左")
        this.forEachIndexed { index, dependencyChain ->
            sb.appendln("${index + 1}. ${dependencyChain.toDetailString()}")
        }
        return sb.toString()
    }
}